//
//  ViewController.m
//  MMLOOK
//
//  Created by dllo on 15/8/24.
//  Copyright (c) 2015年 武俊娥. All rights reserved.
//

#import "ViewController.h"
#import "StyleTableViewCell.h"
#import "NormalTableViewCell.h"
#import "LookJewelryDetailViewController.h"
#import "MMpictureViewController.h"
#import "HoneyViewController.h"
#import "FoodViewController.h"
#import "ShareViewController.h"
#import "ClassViewController.h"
#import "AsynConnect.h"
#import "NormalCostumImageview.h"
#import "SupriseDetailViewController.h"
#import "SearchViewController.h"
#import "HomeHeaderViewController.h"
#import "HeaderTVCell.h"
#import "MJRefresh.h"
#import "MJRefreshNormalHeader.h"
#import "SaveTools.h"
#import "JudgeConnection.h"
#import "Alert.h"
#import "MBProgressHUD.h"
#import "MyView.h"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate,StyleTableViewCellDelegate, HeaderTVCellDelegate, MyViewDelegate>

@property (nonatomic, retain)NSMutableArray *headerArray;
@property (nonatomic, retain)UITableView *table;
@property (nonatomic, retain)NSMutableArray *supriseArray;
@property (nonatomic, retain) MBProgressHUD *mbProView;
@property (nonatomic, copy) NSString *url;
@property (nonatomic, copy) NSString *url1;
@property (nonatomic, retain) NSData *data;
@property (nonatomic, retain) NSData *data1;


@end

@implementation ViewController

- (void)dealloc
{
    [_data release];
    [_data1 release];
    [_url release];
    [_url1 release];
    [_mbProView release];
    [_supriseArray release];
    [_table release];
    [_headerArray release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.url = [@"http://api.liwushuo.com/v1/banners?channel=iOS" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        self.url1 = [@"http://api.liwushuo.com/v1/channels/103/items?gender=2&generation=1&limit=20&offset=0" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        self.headerArray = [NSMutableArray array];
        self.supriseArray = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBar.translucent = NO;
    self.tabBarController.tabBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:253 / 255.0 green:180/255.0 blue:83/255.0 alpha:1];
    self.navigationItem.title = @"首页";
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.backBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil] autorelease];
    
    [self creatTable];
    [self readLocalData];
    [self netConnection];
    [self XLSX];
    
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"sousuo@2x.png"] style:UIBarButtonItemStylePlain target:self action:@selector(buttonAction)] autorelease];
}

- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
    self.tabBarController.tabBar.translucent = NO;
}

//搜索键点击事件
- (void)buttonAction
{
    SearchViewController *search = [[[SearchViewController alloc] init] autorelease];
    [self.navigationController pushViewController:search animated:YES];
}

// 整体table
- (void)creatTable
{
    self.table = [[[UITableView alloc] initWithFrame:CGRectMake(0, 0 , self.view.frame.size.width, self.view.frame.size.height - 114) style:UITableViewStylePlain] autorelease];
    _table.delegate = self;
    _table.dataSource = self;
    _table.showsVerticalScrollIndicator = NO;
    _table.separatorStyle = NO;
    [_table registerClass:[HeaderTVCell class] forCellReuseIdentifier:@"kIdentifier"];
    [self.view addSubview:_table];
}

//设置分区
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

//中间四个button和下面的每日惊喜
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            return self.view.frame.size.width * 288 / 720;
        }
            break;
        case 1:
        {
            return 100 * OffHeight;
        }
            break;
        case 2:
        {
            return self.view.frame.size.width * 328 / 720;
        }
            break;
            
        default:
            break;
    }
    
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section != 0) {
        if ([SaveTools readDataWithName:[_url hash] directory:NSLibraryDirectory]) {
            return 40;
        }
        return 0;
    }
    return 0;
}

//给section加题目 右边button
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if ([SaveTools readDataWithName:[_url hash] directory:NSLibraryDirectory]) {
        
        static NSString *str = @"0. 0";
        MyView *myView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:str];
        
        if (!myView) {
            
            myView = [[[MyView alloc] initWithReuseIdentifier:str] autorelease];
        }
        
        myView.section = section;
        myView.delegate = self;
        
        return myView;
    }
    
    return nil;
}

#warning -----------更多分享
- (void)buttonipAction
{
    if ([JudgeConnection judgeConnection]) {
        
        ShareViewController *share = [[[ShareViewController alloc] init] autorelease];
        [self.navigationController pushViewController:share animated:YES];
    } else {
        
        Alert *alert = [[Alert alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 250) / 2, self.view.frame.size.height * 3 / 4, 250, 50) LabelText:@"当前无网络连接，请检查网络状态"];
        [self.view addSubview:alert];
        [alert release];
    }
}

#warning -----------更多分类
- (void)buttondownAction
{
    if ([JudgeConnection judgeConnection]) {
        
        ClassViewController *class = [[[ClassViewController alloc] init] autorelease];
        [self.navigationController pushViewController:class animated:YES];
    } else {
        
        Alert *alert = [[Alert alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 250) / 2, self.view.frame.size.height * 3 / 4, 250, 50) LabelText:@"当前无网络连接，请检查网络状态"];
        [self.view addSubview:alert];
        [alert release];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        
        if (_headerArray.count == 0) {
            
            return 0;
        } else {
            
            return 1;
        }
    } else if (section == 1) {
        
        return 1;
    } else if (section == 2) {
        
        return _supriseArray.count;
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        HeaderTVCell *headerTVCell = [tableView dequeueReusableCellWithIdentifier:@"kIdentifier"];
        [headerTVCell sendArr:_headerArray];
        headerTVCell.delegate = self;
        return headerTVCell;
    } else if (indexPath.section == 1) {
        
        static NSString *cellIdentity = @"a";
        StyleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentity];
        
        if (!cell) {
            
            cell = [[[StyleTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentity] autorelease];
        }
        
        cell.selectionStyle = UICollectionViewScrollPositionNone;
        cell.delegate = self;
        
        if ([SaveTools readDataWithName:[_url hash] directory:NSLibraryDirectory]) {
            
            cell.flag = YES;
        }
        
        return cell;
    } else if(indexPath.section == 2) {
        
        static NSString *cellIdentity2 = @"normal";
        NormalTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentity2];
        
        if (!cell) {
            
            cell = [[[NormalTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentity2] autorelease];
        }
        
        cell.selectionStyle = UICollectionViewScrollPositionNone;
        NSMutableDictionary *dic = [_supriseArray objectAtIndex:indexPath.row];
        [cell sendarray:dic];
        
        return cell;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2) {
        
        if ([JudgeConnection judgeConnection]) {
            
            SupriseDetailViewController *suprise = [[[SupriseDetailViewController alloc] init] autorelease];
            suprise.supriseDic = [_supriseArray objectAtIndex:indexPath.row];
            suprise.titleStr = [[_supriseArray objectAtIndex:indexPath.row] objectForKey:@"title"];
            [self.navigationController pushViewController:suprise animated:YES];
        } else {
            
            Alert *alert = [[Alert alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 250) / 2, self.view.frame.size.height * 3 / 4, 250, 50) LabelText:@"当前无网络连接，请检查网络状态"];
            [self.view addSubview:alert];
            [alert release];
        }
    }
}

#warning ------------点点乐
- (void)clickStyleWith:(NSInteger)tag
{
    if ([JudgeConnection judgeConnection]) {
        
        switch (tag) {
                
            case 1:
            {
                LookJewelryDetailViewController *lookJewelry = [[LookJewelryDetailViewController alloc] init];
                [self.navigationController pushViewController:lookJewelry animated:YES];
            }
                break;
            case 2:
            {
                MMpictureViewController *mmpicture = [[MMpictureViewController alloc] init];
                [self.navigationController pushViewController:mmpicture animated:YES];
            }
                break;
            case 3:
            {
                HoneyViewController *honey = [[HoneyViewController alloc] init];
                [self.navigationController pushViewController:honey animated:YES];
            }
                break;
            case 4:
            {
                FoodViewController *food = [[FoodViewController alloc] init];
                [self.navigationController pushViewController:food animated:YES];
            }
                break;
                
            default:
                break;
        }
    } else {
        
        Alert *alert = [[Alert alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 250) / 2, self.view.frame.size.height * 3 / 4, 250, 50) LabelText:@"当前无网络连接，请检查网络状态"];
        [self.view addSubview:alert];
        [alert release];
    }
}

- (void)netConnection
{
    [self createMbProView];
    
    [AsynConnect asynConnectWithUrlstr:_url parmater:nil block:^(NSData *data) {
        if (data) {
            self.data = [NSData dataWithData:data];
#warning 缓存
            BOOL saveResult = [SaveTools saveDataWithName:[_url hash] directory:NSLibraryDirectory data:data];// 有网络时 数据储存在本地
            NSLog(@"轮播图存储: %d", saveResult);
            
            [self.headerArray removeAllObjects];
            
            NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSMutableDictionary *littleDic = [dic objectForKey:@"data"];
            NSMutableArray *arr = [littleDic objectForKey:@"banners"];
            
            self.headerArray = [NSMutableArray arrayWithArray:arr];
            
            if (self.data && self.data1) {
                
                [_table reloadData];
                [_mbProView hide:YES];
            }
        }
    }];
    
    [AsynConnect asynConnectWithUrlstr:_url1 parmater:nil block:^(NSData *data) {
        if (data) {
            self.data1 = [NSData dataWithData:data];
            BOOL saveResult = [SaveTools saveDataWithName:[_url1 hash] directory:NSLibraryDirectory data:data];// 有网络时 数据储存在本地
            NSLog(@"每日惊喜存储: %d", saveResult);
            
            [self.supriseArray removeAllObjects];
            
            NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSMutableDictionary *littleDic = [dic objectForKey:@"data"];
            NSMutableArray *arr = [littleDic objectForKey:@"items"];
            
            self.supriseArray = [NSMutableArray arrayWithArray:arr];
            
            if (self.data && self.data1) {
                
                [_table reloadData];
                [_mbProView hide:YES];
            }
        }
    }];
}

- (void)readLocalData
{
    NSData *data = [SaveTools readDataWithName:[_url hash] directory:NSLibraryDirectory];
    if (data) {
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableDictionary *littleDic = [dic objectForKey:@"data"];
        NSMutableArray *arr = [littleDic objectForKey:@"banners"];
        self.headerArray = [NSMutableArray arrayWithArray:arr];
        [_table reloadData];
    }
    
    NSData *data1 = [SaveTools readDataWithName:[_url1 hash] directory:NSLibraryDirectory];
    if (data1) {
        NSMutableDictionary *dic1 = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:nil];
        NSMutableDictionary *littleDic1 = [dic1 objectForKey:@"data"];
        NSMutableArray *arr1 = [littleDic1 objectForKey:@"items"];
        self.supriseArray = [NSMutableArray arrayWithArray:arr1];
        [_table reloadData];
    }
}

- (void)createMbProView
{
    self.mbProView = [[[MBProgressHUD alloc] initWithView:self.view] autorelease];
    _mbProView.mode = MBProgressHUDModeIndeterminate;// 样式 菊花
    _mbProView.labelText = @"加载中. . .";
    [_mbProView show:YES];
    [self.view addSubview:_mbProView];
    [_mbProView hide:YES afterDelay:20];
}

#pragma 下拉刷新
- (void)XLSX
{
    _table.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [_headerArray removeAllObjects];
        [_supriseArray removeAllObjects];
        [self readLocalData];
        [self netConnection];// 处理数据
        [_table reloadData];// 刷新数据
        [_table.header endRefreshing];// 结束刷新
    }];
}

#warning ------------轮播图跳页
- (void)jump:(NSMutableDictionary *)dic
{
    if ([JudgeConnection judgeConnection]) {
        
        HomeHeaderViewController *home = [[[HomeHeaderViewController alloc] init] autorelease];
        home.homedic = dic;
        home.titleStr = [[dic objectForKey:@"target"] objectForKey:@"title"];
        [self.navigationController pushViewController:home animated:YES];
    } else {
        Alert *alert = [[Alert alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 250) / 2, self.view.frame.size.height * 3 / 4, 250, 50) LabelText:@"当前无网络连接，请检查网络状态"];
        [self.view addSubview:alert];
        [alert release];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
